var t = getApp();
var app=getApp()
Page({
    data: {
        checkID: "",
        vote_id: "",
        vote:{},
        canshow:true,
        default_img:'http://bmobfile.funnyfish.cn/2020/05/11/16555bbe40b88c158056807e57232761.png',
        hidden:!0,
        answer:'',
        unitId:'',
        voteIndex:1,
        loading:true,

         doommData: [],
        arrList: t.arrList,
        arrCate: t.arrCate,
        randList:[],
    },
     showImg(t){
        var e = t.currentTarget.dataset.url;
       
        if(!e){return}
        wx.previewImage({
            current: e,
            urls: [ e ]
        });
    },
    onLoad: function(t) {
        var e = this;
        let vid=t.tid
        console.log(t)
        if(!vid){return}
        e.setData({
            vote_id: vid
        })
        var name=wx.getStorageSync('nickName')||'我';
        
        this.setData({
            doommData:[{name:name,info:'查看了问题',good:'刚刚'}]
        })
        wx.showToast({
            title:'加载中...',
            icon:'none'
        })
        e.getVotes(vid);
        var uid=wx.getStorageSync('uid')
        if(uid){
            this.getAnswer(uid,vid)
        }
        this.danmu(35);
        this.getRandList(50);
    },
     huanzi: function (type=1) {//返回弹幕内容
        var that = this
        var zi=[]
        if(type==1){
          zi = that.data.arrList
        }else{
          zi = that.data.arrCate
        }
     
        var ran = Math.floor(Math.random() * zi.length);
        var huanzi = zi[ran];
        return huanzi;
      },
      toDetail(t){
    var e = t.currentTarget.dataset.voteid;
        if(!e){return}
        wx.navigateTo({
            url: "/pages/vote_detail/vote_detail?tid=" + e,
            success: function(t) {
                console.log(t);
            }
        });
      },
    danmu: function (num=30) {//开始弹幕
        var that = this
        var doommData = that.data.doommData || []
        for(var i=0;i<num;i++){
        var name = wx.Als.getRandName();
        
        var huanzi = that.huanzi(1);
        var good = that.huanzi(2);
        var info = "查看了问题";
      
        if (huanzi) {
          info = huanzi;
        }
        var msg={
            name:name,
            info:info,
            good:good
        }
         doommData.push(msg);
        }
       
     
        this.setData({
          doommData: that.data.doommData.concat(doommData)
        })
      },
      getRandList(num=30){
           let that=this;
        let param={
                
               'notlike':{
                        k:'show',
                        v:true
                    },
                    notlike2:{
                        k:'hot',
                        v:1

                    }
        }
        let attr={
            limit:num,
            select:'title,group_count,desc_content,nick_name,avatar',
            order:'-updatedAt',
            gtfield:{
                k:'group_count',
                v:800
            }
          
        }  
        wx.Als.bmobFunc("vote_list", 'all',param,attr).then(res => {
           
            if(res&&res[0]){
        let arr=app.getRandomArrayElements(res,5)

               that.setData({
                randList:arr
               })
            }

        })
      },
    getAnswer(uid,vid){
        let that=this;
        let param={
            uid:uid,
            vid:vid
        }
        let attr={
            limit:1,
          
        }  
        wx.Als.bmobFunc("vote_answer", 'all',param,attr).then(res => {
            if(res&&res[0]){
               
               that.setData({
                   answer:res[0]
               })
            }

        })
    },
    agree: function(t) {
        var e = t.currentTarget.dataset.id, a = this;
        let info=t.currentTarget.dataset.info;
        let type=t.currentTarget.dataset.type;
        let index=t.currentTarget.dataset.index;
        if(info){
            info=Number(info)
        }
     
        var uid=wx.getStorageSync('uid');
            console.log(info);
          
        if(!e||!uid||this.data.canshow==false){return}
        wx.showToast({
          title: '提交中...',
          icon:'none'
        })
        let param={
            uid:uid,
            vid:e
        }
        let attr={
            limit:1
        }
        this.setData({
            canshow:false
        })
        wx.Als.bmobFunc('vote_answer','all',param,attr).then(res=>{
           
            if(res&&res.length==0){
                a.add_vote(uid,e,info,index,type);
                var voteinfo=a.data.vote
                voteinfo.group_count=voteinfo.group_count+1;
                var content=type;
                var  contentinfo='vote_content'+content;
                app.addVoteNum(uid);
                voteinfo[contentinfo]= voteinfo[contentinfo]+1;
                a.setData({
                    vote:voteinfo,
                    answer:{content:content,uid:uid}
                })
               
            }else{
                wx.showToast({
                  title: '已经回答',
                  icon:'none'
                })
            }

        })
        setTimeout(function(res){
            a.setData({
              canshow:true
            })
          },1000);
    },
    update_list(aid,vid,content=1){
let query = wx.Bmob.Query('vote_list');
const pointer = wx.Bmob.Pointer('vote_answer')
const relID = pointer.set(aid)
content=Number(content)
// const relation = wx.Bmob.Relation('vote_answer') // 需要关联的表
// const relID = relation.add([aid,"vid"]) 
query.get(vid).then(res => {
  console.log(res)
  console.log("udpate")
  let c='vote_content'+content;
  let num1=Number(res[c])+1;
  console.log(num1);
  console.log("====")
  let num2=Number(res.group_count)+1;
 res.set('vote_content'+content,num1);
 res.set('group_count',num2);
 res.set('newid',relID); 
   res.save();

}).catch(err => {
  console.log(err)
})
    },
    add_vote(uid,vid,content1='',index=0,type=1){
        let a=this;
        let content=Number(content1)
     
        let param={
            uid:uid,
            vid:vid,
            content:content
        }
        wx.Als.bmobFunc('vote_answer', 'add', param).then(res => {
          
           
            let uid=wx.getStorageSync('uid')
            if(res){
                let answer={
                    uid:uid,
                    content:content,
                    vid:vid
                }
                a.setData({
                    answer:answer
                })
                a.update_list(res.objectId,vid,content);
            }
           
          })
    },

    add_list(title,content1,content2,vote_content1=0,vote_content2=0,avatar=''){
        let that=this;
        if(!title||!vote_content2)return;
        var nick_name=wx.getStorageSync('nickName');
   
        var uid=wx.getStorageSync('uid');
        var group_count=Number(vote_content1)+Number(vote_content2)
        let param2={
            title:title
        }
        wx.showLoading({
            title: '添加中...',
          })
          let param={
            uid:uid,
            title:title,
            content1:content1,
            content2:content2,
            group_count:group_count,
            vote_content1:vote_content1,
            vote_content2:vote_content2,
            idlist:[],
            nick_name:nick_name,
            avatar:avatar,
            
          }
        wx.Als.bmobFunc('vote_list','all',param2).then(res=>{
            if(res.length>0){
                return;
            }else{
                wx.Als.bmobFunc('vote_list', 'add', param).then(res => {
                    console.log(res)
                    console.log(res)
                    wx.hideLoading();
                    if(res){
                    
                      wx.showToast({
                        title: '添加成功~',
                      })
              
                    }
                  })
            }
        })
    
      
      
     },
    onVote: function(t) {
        var e = t.currentTarget.id.split("-"), o = this, a = wx.getStorageSync("FTE_ID"), n = "";
        "" != a && (n = "FTE_ID=" + a), wx.showLoading({
            title: "投票中..."
        }), wx.request({
            url: getApp().globalData.api_url + "/zxf/appclient/attitude_xz.php?act=vote",
            header: {
                "content-type": "application/x-www-form-urlencoded",
                cookie: n
            },
            method: "POST",
            data: {
                topic_id: e[0],
                vote_content: e[1]
            },
            success: function(t) {
                if (wx.hideLoading(), 0 == t.data.result) {
                    for (var a = o.data.votes, n = 0; n < a.length; n++) for (var i = 0; i < a[n].group_by.length; i++) a[n].id == e[0] && (a[n].is_vote = 1, 
                    a[n].vote_content = e[1], a[n].group_by[i].vote_content == e[1] ? a[n].group_by[i].prec = o.Percentage(parseInt(a[n].group_by[i].count) + 1, parseInt(a[n].group_count) + 1) : a[n].group_by[i].prec = o.Percentage(parseInt(a[n].group_by[i].count), parseInt(a[n].group_count) + 1));
                    o.setData({
                        checkID: e[0],
                        votes: a
                    });
                } else 1009 == t.data.result ? (wx.setStorageSync("avatarUrl", ""), wx.setStorageSync("nickName", ""), 
                wx.showToast({
                    title: t.data.msg,
                    icon: "none",
                    duration: 1e3,
                    mask: !0
                }), setTimeout(function() {
                    getApp().globalData.from_vote = 2, getApp().globalData.detail_id = e[0], wx.navigateTo({
                        url: "/pages/login/index"
                    });
                }, 700)) : wx.showToast({
                    title: t.data.msg,
                    icon: "none",
                    duration: 1e3,
                    mask: !0
                });
            },
            fail: function() {
                wx.hideLoading(), wx.showToast({
                    title: "投票失败，请稍后再试",
                    icon: "none",
                    duration: 1500,
                    mask: !0
                });
            }
        });
    },
    onShow(){
        if(app.config.qqad){
            this.setData({
                unitId:app.config.qqad
            })
        }
    },
    goHome(){
        wx.redirectTo({
          url: 'pages/index/index',
        })
    },
    onShareAppMessage: function(t) {
        var e = wx.getStorageSync("uid"), a = t.target.dataset.voteid, o = wx.getStorageSync("nickName")|| "朋友";
        return "button" === t.from && console.log(t), {
            title: o + "邀你投一票！",
            path: "/pages/vote_detail/vote_detail?shareFrom=share&uid=" + e + "&tid=" + a,
            success: function(t) {}
        };
    },
    goHome(){
        wx.switchTab({
          url: '/pages/index/index',
        })
    },
    getVotes: function(e) {
        let that=this
        let param = {
            objectId: e,
           
          }
    
          var attr = {
            limit:1
          }
    
    
          wx.Als.bmobFunc('vote_list', 'all', param, attr).then(ret => {
            console.log(ret);

          let res=ret[0]
          if(res&&ret[0]){
          
           that.setData({
               vote:res
           })
           
          }
           
    
    
          }).catch(err => {
            console.log(err)
          })
    },
    Percentage: function(t, e) {
        return 0 == e ? 0 : (Math.round(t / e * 1e4) / 100).toFixed(0);
    },
    clickCollect: function(e) {
      
    }
});